<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
class Check extends Common
{
    /**审核员列表
     * URL：admin/check/lists
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('performance_check')->alias('pc')
                ->join('teacher t','t.id=pc.teacher_id','left')
                ->field('pc.*,t.teacher_no,t.true_name')
                ->where('pc.is_del',0)
                ->where('true_name|teacher_no', 'like', "%" . $keyword . "%")
                ->order('pc.create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {

                foreach ($list['data'] as $k => $v) {

                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    //分配部门管理
                    if ($v['section_ids']){
                        $section_ids = unserialize($v['section_ids']);
                        $str = '';
                        foreach ($section_ids as $k1=>$v1){
                            $t = Db::name('section')->where('section_id',$v1)->value('title');
                            $str .= $t.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                        }
                        $list['data'][$k]['section_ids'] = $str;
                    }

                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('check_list');
    }

    /**
     * 查找审核员
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function check_search(){

        if(Request::isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));
            $list = Db::name('teacher')
                ->field('id,teacher_no,true_name')
                ->where('is_del',0)
                ->where('id','neq',1)
                ->where('true_name|teacher_no', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch('checkForm');
    }

    /**
     * 添加审核员
     */
    public function checkAdd(){
        $data['teacher_id'] = input('post.id');
        $data['is_second'] = input('post.flag');

        $data['create_time'] = time();
        $re = Db::name('performance_check')->insert($data);
        $true_name = Db::name('teacher')->where('id',$data['teacher_id'])->value('true_name');
        $log = [
            'content'=>'添加审核人'.$true_name
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success("设定成功",'lists');
        }
    }

    /**
     * 分配部门
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function distribution_section(){

        $id = (int)input('id');

        if (request()->isAjax()) {
            $data = input('post.');
            $data['section_ids'] = serialize($data['section_ids']);
            $re = Db::name('performance_check')->where('id',$id)->update($data);
            $true_name = Db::name('performance_check pc')->join('teacher t','t.id=pc.teacher_id')->where('pc.id',$id)->value('t.true_name');
            $log = [
                'content'=>'编辑审核部门'.$true_name
            ];
            $wed = new Weblog();
            $wed->insert($log);

            if(!$re){
                $this->error('编辑失败');
            }
            $this->success("编辑成功",'lists');

        }

        $sections = '';
        $info = Db::name('performance_check')->where('id',$id)->find();

        if($info['section_ids']){
            $ids = implode(',',unserialize($info['section_ids']));
            $sections = Db::name('section')->field('section_id,title,pid')
                ->where('section_id','in',$ids)->select();
        }

        $this->assign('check_id',$id);
        $this->assign('sections',$sections);
        return $this->fetch('distribution_section');

    }

    /**
     * 部门展示
     * @return array
     * @throws \think\exception\DbException
     */
    function section_list(){

        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('section')
                ->where('is_del',0)
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

    }

    /**删除审核员
     * URL：admin/check/checkDel
     * @throws
     * @return array
     */
    public function checkDel(){
        $id=input('post.id');
        if (session('aid')==1){
            $re = Db::name('performance_check')->where('id',$id)->update(['is_del'=>1]);
            $true_name = Db::name('performance_check pc')->join('teacher t','t.id=pc.teacher_id')->where('pc.id',$id)->value('t.true_name');
            $log = [
                'content'=>'删除审核人'.$true_name
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($re && $res){
                $this->success('删除成功!');
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error('您没有删除审核人的权限!');
        }
    }




    /****************************审核列表**********************************************************/

    /**
     * 审核列表
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

//          审核人员信息
            $info = Db::name('performance_check')
                ->where('is_del',0)
                ->where('teacher_id',session('aid'))
                ->field('id,teacher_id as t_id,section_ids,is_second')
                ->find();

            if (!empty($info)&&$info&&$info['section_ids']) {

                //查找部门下的所有教师
                $section_ids = implode(',',unserialize($info['section_ids']));

                $arr = Db::name('teacher t')
                    ->join('section s','t.section_id=s.section_id')
                    ->where('t.true_name|t.teacher_no|s.title', 'like', "%" . $keyword . "%")
                    ->where('t.section_id','in',$section_ids)
                    ->field('t.id as teacher_id,t.teacher_no,t.true_name,t.section_id,s.title')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();

                //查找今日可以编辑的考核项周期
                $cycle_data = Db::name('cycle')->where('status',1)->select();

                if($cycle_data) {
                    $str_cycle_ids = '';
                    foreach ($cycle_data as $k => $v) {

                        if ($v['id'] == 1) {

                            $today = (int)date("d", time());
                            if ((int)$v['start_time'] <= $today && (int)$v['end_time'] >= $today) {
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        } elseif ($v['id'] == 2) {
                            $today = date("m-d", time());
                            if ($v['start_time'] && $v['end_time']) {
                                $start_time = unserialize($v['start_time']);
                                $end_time = unserialize($v['end_time']);
                                if ((($today >= $start_time[0]) && ($today <= $end_time[0])) || (($today >= $start_time[1]) && ($today <= $end_time[1]))) {
                                    $str_cycle_ids .= ','.$v['id'];
                                }
                            }
                        }elseif ($v['id'] == 3) {
                            $today = date("m-d",time());

                            if($v['start_time'] && $v['end_time'] && ($today>=$v['start_time'])&&($today<=$v['end_time'])){
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        }
                    }

                    $tongji['zong'] = $arr['total'];
                    $tongji['dai'] = 0;
                    $tongji['tong'] = 0;
                    $tongji['bo'] = 0;

                    //拿到所有教师
                    $teachers = Db::name('teacher t')
                        ->join('section s','t.section_id=s.section_id')
                        ->where('t.true_name|t.teacher_no|s.title', 'like', "%" . $keyword . "%")
                        ->where('t.section_id','in',$section_ids)
                        ->field('t.id as teacher_id,t.teacher_no,t.true_name,t.section_id,s.title')
                        ->select();

                    foreach ($teachers as $k2=>$v2) {

//                    拿到教师职务
                        $position_ids = Db::name('teacher')->where('id',$v2['teacher_id'])->value('position_id');

                        if($position_ids){
                            $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                        }

//                    根据职务拿到考核项分类ids
                        $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                        $str_performance_cate_ids = '';
                        if($performance_cate_ids){
                            foreach ($performance_cate_ids as $k=>$v){
                                if($v['performance_cate_ids']){
                                    $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                                }

                            }
                        }
                        $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));

//                    根据考核项分类ids和可编辑周期拿到可编辑考核项分类ids
                        $cate_list = Db::name('performance_cate')->where('cycle_id','in',$str_cycle_ids)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                        //自己的审核结果 待审核  通过  驳回
                        $teachers[$k2]['dai']  = 0;
                        $teachers[$k2]['tong']  = 0;
                        $teachers[$k2]['bo'] = 0;
                        //自己上一级的审核结果 待审核  通过  驳回
                        $teachers[$k2]['shang_dai'] = 0;
                        $teachers[$k2]['shang_bo']   = 0;
                        $teachers[$k2]['shang_tong'] = 0;
                        //录入员的录入结果 待录入  保存待提交  已提交
                        $teachers[$k2]['lu_dai'] = 0;
                        $teachers[$k2]['lu_cun'] = 0;
                        $teachers[$k2]['lu_jiao'] = 0;

                        if($cate_list){

                            foreach ($cate_list as $k=>$v){

                                $answer = Db::name('answer_record')->where('teacher_id',$v2['teacher_id'])->where('performance_cate_id',$v['cate_id'])->find();

                                if($answer){

                                    if($answer['entry_submit_status']=='0'){
                                        $teachers[$k2]['lu_dai'] = (int)$teachers[$k2]['lu_dai']+1;
                                    }elseif ($answer['entry_submit_status']==1){
                                        $teachers[$k2]['lu_cun'] = (int)$teachers[$k2]['lu_cun']+1;
                                    }else{
                                        $teachers[$k2]['lu_jiao'] = (int)$teachers[$k2]['lu_jiao']+1;
                                        if($answer['status']=='0'){
                                            $teachers[$k2]['dai'] = (int)$teachers[$k2]['dai']+1;
                                        }elseif ($answer['status']==1){
                                            $teachers[$k2]['tong'] = (int)$teachers[$k2]['tong']+1;
                                            if($answer['second_status']=='0'){
                                                $teachers[$k2]['shang_dai'] = (int)$teachers[$k2]['shang_dai']+1;
                                            }elseif ($answer['second_status']==1){
                                                $teachers[$k2]['shang_tong'] = (int)$teachers[$k2]['shang_tong']+1;

                                            }else{
                                                $teachers[$k2]['shang_bo'] = (int)$teachers[$k2]['shang_bo']+1;
                                            }
                                        }else{
                                            $teachers[$k2]['bo'] = (int)$teachers[$k2]['bo']+1;
                                        }
                                    }

                                }else{
                                    $teachers[$k2]['dai'] = (int)$teachers[$k2]['dai']+1;
                                }

                            }
                        }

                        $teachers[$k2]['self_check_detail']  = '暂无';
                        $teachers[$k2]['shang_check_detail'] = '暂无';
                        $teachers[$k2]['lu_check_detail']    = '暂无';

                        if($teachers[$k2]['dai']==0&&$teachers[$k2]['bo']==0){
                            if($teachers[$k2]['tong']!=0){
                                $teachers[$k2]['self_check_detail'] = '已完成';
                            }
                        }else{
                            $teachers[$k2]['self_check_detail'] = '待审核：'.$teachers[$k2]['dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;驳回：'.$teachers[$k2]['bo'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;通过：'.$teachers[$k2]['tong'];
                        }

                        if($teachers[$k2]['shang_dai']==0&&$teachers[$k2]['shang_bo']==0){
                            if($teachers[$k2]['shang_tong']!=0){
                                $teachers[$k2]['shang_check_detail'] = '已完成';
                            }
                        }else{
                            $teachers[$k2]['shang_check_detail'] = '待审核：'.$teachers[$k2]['shang_dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;驳回：'.$teachers[$k2]['shang_bo'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;通过：'.$teachers[$k2]['shang_tong'];
                        }

                        if($teachers[$k2]['lu_dai']==0&&$teachers[$k2]['lu_cun']==0){
                            $teachers[$k2]['status_detail'] = '已完成';
                        }else{
                            $teachers[$k2]['lu_check_detail'] = '待处理：'.$teachers[$k2]['lu_dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;保存待提交：'.$teachers[$k2]['lu_cun'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已提交：'.$teachers[$k2]['lu_jiao'];
                        }

                        if($info['is_second']==2){

                            if((int)$teachers[$k2]['dai']>0){
                                $tongji['dai'] = $tongji['dai']+1;
                            }

                            if((int)$teachers[$k2]['tong']>0){
                                $tongji['tong'] = $tongji['tong']+1;
                            }

                            if((int)$teachers[$k2]['bo']>0){
                                $tongji['bo'] = $tongji['bo']+1;
                            }
                        }else{

                            if((int)$teachers[$k2]['shang_dai']>0){
                                $tongji['dai'] = $tongji['dai']+1;
                            }

                            if((int)$teachers[$k2]['shang_tong']>0){
                                $tongji['tong'] = $tongji['tong']+1;
                            }

                            if((int)$teachers[$k2]['shang_bo']>0){
                                $tongji['bo'] = $tongji['bo']+1;
                            }
                        }

                    }

                    foreach ($arr['data'] as $k=>$v) {

                        foreach ($teachers as $k1=>$v1) {

                            if($v['teacher_id'] == $v1['teacher_id']){
                                $arr['data'][$k] = $v1;
                            }

                        }

                    }
                }

                return $result = ['code'=>0,'msg'=>'成功!','data'=>$arr['data'],'count'=>$arr['total'],'tongji'=>'待审核：'.$tongji['dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;驳回：'.$tongji['bo'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;通过：'.$tongji['tong']];
            }else{
                return $result = ['code'=>0,'msg'=>'成功!','data'=>'','count'=>0,'tongji'=>'待审核：0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;驳回：0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;通过：0'];

            }


        }

        $info = Db::name('performance_check')
            ->where('is_del',0)
            ->where('teacher_id',session('aid'))
            ->field('id,teacher_id as t_id,section_ids,is_second')
            ->find();
        $this->assign('is_second',$info['is_second']);

        return $this->fetch();
    }


    /**
     * 个人考核项审核
     */
    public function check_teacher(){

        $teacher_id = input('get.teacher_id');

        if (request()->isAjax()) {

            //查找今日可以编辑的考核项周期
            $cycle_data = Db::name('cycle')->where('status',1)->select();

            //          审核人员信息
            $info = Db::name('performance_check')
                ->where('is_del',0)
                ->where('teacher_id',session('aid'))
                ->field('id,teacher_id as t_id,section_ids,is_second')
                ->find();

            if($cycle_data) {
                $str_cycle_ids = '';
                foreach ($cycle_data as $k => $v) {

                    if ($v['id'] == 1) {

                        $today = (int)date("d", time());
                        if ((int)$v['start_time'] <= $today && (int)$v['end_time'] >= $today) {
                            $str_cycle_ids .= ','.$v['id'];
                        }
                    } elseif ($v['id'] == 2) {
                        $today = date("m-d", time());
                        if ($v['start_time'] && $v['end_time']) {
                            $start_time = unserialize($v['start_time']);
                            $end_time = unserialize($v['end_time']);
                            if ((($today >= $start_time[0]) && ($today <= $end_time[0]))
                                || (($today >= $start_time[1]) && ($today <= $end_time[1]))) {
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        }
                    }elseif ($v['id'] == 3) {
                        $today = date("m-d",time());

                        if($v['start_time'] && $v['end_time'] && ($today>=$v['start_time'])&&($today<=$v['end_time'])){
                            $str_cycle_ids .= ','.$v['id'];
                        }
                    }
                }


//                    拿到教师职务
                $position_ids = Db::name('teacher')->where('id',$teacher_id)->value('position_id');

                if($position_ids){
                    $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                }

//                    根据职务拿到考核项分类ids
                $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                $str_performance_cate_ids = '';
                if($performance_cate_ids){
                    foreach ($performance_cate_ids as $k=>$v){
                        if($v['performance_cate_ids']){
                            $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                        }

                    }
                }
                $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));

//                    根据考核项分类ids和可编辑周期拿到可编辑考核项分类ids
                $cate_list = Db::name('performance_cate')->where('cycle_id','in',$str_cycle_ids)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                if($cate_list){
                    foreach ($cate_list as $k=>$v){

                        $answer = Db::name('answer_record')->where('teacher_id',$teacher_id)->where('performance_cate_id',$v['cate_id'])->find();

                        $cate_list[$k]['status'] = '尚未提交';
                        if($info['is_second']==2){
                            if($answer){
                                if($answer['entry_submit_status']==2){
                                    $cate_list[$k]['status'] = $answer['status'];
                                }
                            }
                        }else{
                            if($answer){
                                if($answer['status']==1){
                                    $cate_list[$k]['status'] = $answer['second_status'];
                                }
                            }
                        }

                    }
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$cate_list,'count'=>count($cate_list)];
        }
        $this->assign('teacher_id',$teacher_id);
        return $this->fetch('check_teacher');
    }



    /**ajax请求对应题目分类下的题目数据
     * 具体考核项审核
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check_teacher_show(){

        $cate_id    = input('get.cate_id');
        $teacher_id = input('get.teacher_id');

        //          审核人员信息
        $info = Db::name('performance_check')
            ->where('is_del',0)
            ->where('teacher_id',session('aid'))
            ->field('id,teacher_id as t_id,section_ids,is_second')
            ->find();

        if($info['is_second']==2){
            $status = Db::name('answer_record')->where('teacher_id',$teacher_id)
                ->where('performance_cate_id',$cate_id)->value('status');
        }else{
            $status = Db::name('answer_record')->where('teacher_id',$teacher_id)
                ->where('performance_cate_id',$cate_id)->value('second_status');
        }

        if(Request::isAjax()) {
            $cate_id    = input('get.cate_id');
            $teacher_id = input('get.teacher_id');

            //拿到该题目分类下的题目
            $performance_ids = Db::name('performance_cate')->where('cate_id',$cate_id)->value('performance_ids');
            $performance_ids = implode(',',unserialize($performance_ids));
            //查找题目并进行数据处理
            $list = Db::name('performance')->where('title_id','in',$performance_ids)->select();
            foreach ($list as $k=>$v){
                //没有做题时渲染题目
                $list[$k]['answer'] = '';
                $list[$k]['var_content'] = json_decode($v['var_content'],true);
            }

            //通过$cate_id去数据库比对该教师是否已经做过了该题
            $info = Db::name('answer_record')->where('teacher_id',$teacher_id)->where('performance_cate_id',$cate_id)->find();

            if (!empty($info)){
                $info['entry_answer_content'] = unserialize($info['entry_answer_content']);
            }

            //如果存在
            if($info['entry_answer_content']){
                foreach ($list as $k=>$v){
                    foreach ($info['entry_answer_content'] as $k1=>$v1){

                        if ($v['title_id'] == $v1['tiu_id']){
                            $list[$k]['answer'] = $v1['answer'];
                        }
                    }
                }
            }

            $data['list'] = $list;
            return json($data);
        }

        $this->assign('cate_id',$cate_id);
        $this->assign('teacher_id',$teacher_id);
        $this->assign('status',$status);

        return $this->fetch('check_teacher_show');
    }

    //保存审核状态
    public function save(){
        $teacher_id = input('get.teacher_id');
        $cate_id = input('get.cate_id');
        $status = input('get.flag');
        if (input('post.reject_reason')){
            $reject_reason = input('post.reject_reason');
        }

        //          审核人员信息
        $info = Db::name('performance_check')
            ->where('is_del',0)
            ->where('teacher_id',session('aid'))
            ->field('id,teacher_id as t_id,section_ids,is_second')
            ->find();

        if($info['is_second']==2){
            $re = Db::name('answer_record')
                ->where('teacher_id',$teacher_id)
                ->where('performance_cate_id',$cate_id)
                ->update(['status'=>$status,'check_time'=>time(),'reject_reason'=>$reject_reason]);
        }else{

            $re = Db::name('answer_record')
                ->where('teacher_id',$teacher_id)
                ->where('performance_cate_id',$cate_id)
                ->update(['second_status'=>$status,'check_time'=>time(),'second_reject_reason'=>$reject_reason]);
        }

        if ($status==1){
            $status1='通过';
        }else{
            $status1='驳回';
        }
        $true_name = Db::name('teacher')->where('id',$teacher_id)->value('true_name');
        $title = Db::name('performance_cate')->where('cate_id',$cate_id)->value('title');
        $log = [
            'content'=>'审核项'.$title.$true_name.$status1
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success('保存成功',url('check_teacher'),$teacher_id);
        }else{
            $this->error('保存失败');
        }

    }
}